package com.wx.oauth.interceptor;

import static com.wx.oauth.constants.WXConstants.*;

import com.wx.oauth.utils.CookieUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * 通过拦截器进行重定向
 *
 * @author Chenhaowen
 * @since 2019/8/5 20:31.
 */
public class WXOAuthInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(WXOAuthInterceptor.class);

    /**
     * 授权地址
     */
    private static String authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";


    /**
     * 微信授权方式 :应用授权作用域，snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid）
     * snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。并且，
     * 即使在未关注的情况下，只要用户授权，也能获取其信息
     */
    private static String SCOPE = "snsapi_base";

    /**
     * 微信授权获取登录凭证code接口
     */
    private static String REDIRECT_URI = "http://sunnyer.free.idcfengye.com/oauth/auth?redirect=REDIRECT_URL";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String openid = "";
        if (cookies != null) {
            //这里是根据cookie的key获取value
            openid = CookieUtils.getValByKey(COOKIE_KEY, cookies);
            System.out.println("openid"+openid);
        }
        LOGGER.debug("拦截------------------------");
        if (StringUtils.isEmpty(openid)) {
            LOGGER.debug("ready to oauth WeChat");
            String queryString = request.getQueryString();
            String redirectUrl = "";
            if (!StringUtils.isEmpty(queryString)) {
                redirectUrl = request.getRequestURL() + "?" + request.getQueryString();
            }
            String url = authUrl.replace("APPID", APPID).replace("SCOPE", SCOPE).replace("REDIRECT_URI", URLEncoder.encode(REDIRECT_URI.replace("REDIRECT_URL", redirectUrl), "utf-8"));
            response.sendRedirect("/qrcode/generateqrcode?url="+
                    URLEncoder.encode(url,"utf-8"));
            return false;
        }
        return super.preHandle(request, response, handler);
    }
}
